<template>
    <div id="app">
        <div>
            <p class="p1">总人数：{{ students.length }}，抽取<input v-model="num" />人</p>
        </div>
        <button :class="intervalId ? '' : 'selectBtn'" @click="selectStudents">{{ btnText }}</button>
        <ul>
            <li v-for="(item, i) in students" :key="i" :class="{ current: selectedStudentsIndex.includes(i) }">{{ item
            }}
            </li>
        </ul>
    </div>
</template>

<script>
export default {
    data() {
        return {
            num: '',
            intervalId: '',
            selectedStudentsIndex: "",
            students: [
                "肉末豌豆",
                "肉末茄子",
                "麻婆豆腐",
                "尖椒肉丝",
                "芹菜肉丝",
                "香干肉丝",
                "鸡蛋肉片",
                "黄瓜鸡蛋",
                "黄瓜肉片",
                "白菜肉片",
                "木耳肉片",
                "土豆丝肉丝",
                "豆芽肉丝",
                "清炒白菜",
                "西红柿鸡蛋",
                "火爆大头菜",
                "酸辣土豆丝",
                "孜然蘑菇",
                "咖喱鸡",
                "鸡蛋羹",
                "清炒豆芽",
                "清炒油菜",
                "水煮肉片",
                "炒花菜",
                "香肠炒蛋",
                "酸菜五花肉",
            ],
        }
    },
    computed: {
        btnText() {
            return this.intervalId ? '确定选择' : `点击随机抽取 ${this.num} 位`
        },
    },
    created() {
        // 每次刷新页面打乱姓名排序
        this.students.sort(() => 0.5 - Math.random())
        // 当前名单的索引数组
        this.studentsIndex = this.students.map((v, i) => i)
    }, methods: {

        selectStudents() {
            // 如果未开启定时器
            if (!this.intervalId) {
                this.intervalId = setInterval(() => {
                    // 获取到随机选中的学员索引数组
                    this.selectedStudentsIndex = this.studentsIndex.sort(() => 0.5 - Math.random()).slice(0, this.num)
                }, 100)
            }
            // 开启了定时器
            else {
                clearInterval(this.intervalId)
                this.intervalId = null
            }
        }
    }
}
</script>

<style>
* {
    margin: 0;
    padding: 0;
}

body {
    background-color: #232323;
    color: #fff;
}

.p1{
    position: absolute;
    top: 7%;
}
ul li {
    display: inline-block;
    padding: 10px;
    margin-right: 5px;
    border: 1px solid #fff;
    border-radius: 21px;
    color: #fff;
}

input {
    width: 45px;
}

button {
    position: relative;
    top: 0;
    left: 50%;
    width: 90px;
    height: 50px;
    transform: translateX(-50%);
    margin: 70px 0;
    border-radius: 25px;
}

.current {
    color: #000;
    background-color: #fff;
    transform: scale(1.2);
    transition: all .3s;
}

.selectBtn {
    width: 130px;
    border-color: #fff;
    background-color: #232323;
    color: #fff;
}
</style>